const express = require("express");
const app = express()

const got = require('got');
var fs = require("fs")

const config = require("./config.js");
let { appid, appsecret, filePath } = config;

class Token {
	constructor(appid, appsecret) {
		this.appid = appid;
		this.appsecret = appsecret;
		this.filePath = filePath;
		this.init()
	}

	//初始化
	async init() {
		var result = this.get();
		if (!result) {
			var result = await this.create()
		}
		return result;

	}
	/*
		创建新的access_token
		@return 返回token
	*/
	async create() {
		var url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.appid}&secret=${this.appsecret}`
		const response = await got(url);
		var obj = JSON.parse(response.body);
		obj.addtime = new Date().getTime();
		fs.writeFileSync(this.filePath, JSON.stringify(obj));
		return obj.access_token;
	}

	/*
		读取access_token
		@return 如果过期返回false；否则返回返回token
	*/
	get() {
		//打开本地文件，检测token是否过期
		const content = fs.readFileSync(this.filePath)
		var obj = JSON.parse(content);
		var nowtime = new Date().getTime()

		if (nowtime >= obj.addtime + 7200 * 1000) {
			return false;
		}
		return obj.access_token;
	}

}

var model = new Token(appid, appsecret)
var token = model.init();
module.exports = token;


